package com.iocollege.tinyframe.service.system.impl;

import com.iocollege.tinyframe.common.core.constant.UserStatus;
import com.iocollege.tinyframe.common.core.domain.LoginUser;
import com.iocollege.tinyframe.common.exception.BaseException;
import com.iocollege.tinyframe.entity.system.SysRole;
import com.iocollege.tinyframe.entity.system.SysUser;
import com.iocollege.tinyframe.service.system.SysRoleService;
import com.iocollege.tinyframe.service.system.SysUserService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 用户验证处理
 *
 * @author ruoyi
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    @Autowired
    private SysUserService userService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private SysRoleService sysRoleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        List<SysUser> userList = userService.findByAttrName("user_name",username);
        SysUser user;
        if (userList.size()==0) {
            log.info("登录用户：{} 不存在.", username);
            throw new UsernameNotFoundException("登录用户：" + username + " 不存在");

        } else{
            user=userList.get(0);
            if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
                log.info("登录用户：{} 已被删除.", username);
                throw new BaseException("对不起，您的账号：" + username + " 已被删除");
            } else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
                log.info("登录用户：{} 已被停用.", username);
                throw new BaseException("对不起，您的账号：" + username + " 已停用");
            }
        }

        return createLoginUser(user);
    }

    public UserDetails createLoginUser(SysUser user) {

        //读取用户的角色
        List<SysRole> sysRoles = sysRoleService.selectRolesByUserId(user.getId());
        return new LoginUser(user, permissionService.getMenuPermission(user),sysRoles);

    }
}
